<template>

  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="query">
        <el-form-item>
          <el-input v-model="query.keywords" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="exportData">导出</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="handleImport">导入</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="dataList" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="40">
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="120" sortable>
      </el-table-column>
      <el-table-column prop="headImage" label="头像" width="180" sortable>
        <template scope="scope">
          <img :src="scope.row.headImage" width="80px">
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="250" sortable>
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="80" sortable>
      </el-table-column>
      <el-table-column prop="department.name" label="所属部门"  sortable>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="total, sizes, prev, pager, next, jumper" @current-change="handleCurrentChange"
                     :page-sizes="[5, 10, 20, 50]"  @size-change="handleSizeChange"
                     :page-size="pageSize" :total="total" style="float:right;">
      </el-pagination>
    </el-col>

    <!-- 添加和编辑界面 -->
    <el-dialog :title="title" :visible.sync="formVisible" :close-on-click-modal="false">
      <el-form :model="employeeForm" label-width="100px" :rules="employeeFormRules" ref="employeeForm">
        <el-form-item label="员工用户名" prop="username">
          <el-input v-model="employeeForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="employeeForm.email"></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="employeeForm.age"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <el-input v-model="employeeForm.headImage"></el-input>
        </el-form-item>
        <el-form-item label="所属部门">
          <el-select v-model="employeeForm.department" value-key="id" clearable filterable placeholder="请选择">
            <el-option
                v-for="dep in deps"
                :key="dep.id"
                :label="dep.name"
                :value="dep">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="formVisible = false">取消</el-button>
        <el-button type="primary" @click.native="formSubmit" :loading="employeeFormLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--  导入弹出框  -->
    <el-dialog :title="title" :visible.sync="uploadVisible" :close-on-click-modal="false">
      <el-form :model="employeeForm" label-width="100px"  ref="employeeForm">
        <el-form-item>
          <el-upload
              class="upload-demo"
              ref="upload"
              action=""
              multiple
              accept=".xlsx,xls"
              :limit="3"
              :auto-upload="false"
              :file-list="fileList"
              :on-remove="handleRemove"
              :on-exceed="handleExceed"
              :http-request="httpRequest"
              :on-preview="handlePreview"
              :before-remove="beforeRemove">
            <el-button slot="trigger" type="success">上传文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传excel文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="uploadVisible = false">取消</el-button>
        <el-button type="primary" @click.native="submitUpload">提交</el-button>
      </div>
    </el-dialog>

  </section>

</template>

<script>
import util from "../../common/js/util";
import {addUser, batchRemoveUser} from "../../api/api";
import Login from "../Login";

export default {
  name:"Employee",
  data(){
    return {
      uploadVisible:false,
      fileList:[],
      query:{
        keywords:"",
      },
      dataList:[],
      listLoading:false,
      sels:[],
      total:0,
      currentPage: 1,
      pageSize:10,
      title:"",
      formVisible:false,
      //编辑界面数据
      employeeForm: {
        id: null,
        username: null,
        password:null,
        headImage:null,
        email:null,
        age:null,
        department_id:null,
        department:null
      },
      employeeFormRules: {
        username: [
          { required: true, message: '请输入所属部门', trigger: 'blur' }
        ]
      },
      employeeFormLoading:false,
      deps:[],
      deptTree:[]
    }
  },
  methods:{
    batchRemove(){
      // 触发批量删除操作
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        // let para = { ids: ids };
        this.$http.patch("emp",ids).then((res) => {
          this.listLoading = false;
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.loadListData();
        });
      }).catch(() => {
      });
    },
    formSubmit(){
      this.$refs.employeeForm.validate((valid) => {
        if (valid) {  // 通过了表单验证
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            // 确认框
            this.employeeFormLoading = true;
            this.$http.put("/emp",this.employeeForm).then((res) => {
              if(res.data.success){
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
              }else {
                this.$message.error(res.data.message);
              }
              this.formVisible = false;
              this.loadListData();
              this.employeeFormLoading = false;
            });
          });
        }
      });
    },
    search(){
      this.currentPage=1;
      this.loadListData();
    },
    handleAdd(){
      this.title = "新增";
      // 清空表单数据
      this.employeeForm = {
          id: null,
          username: null,
          password:null,
          headImage:null,
          email:null,
          age:null,
          department_id:null,
          department:null
      }
      // 打开弹出框
      this.formVisible = true;
    },
    selsChange(sels){
      this.sels = sels;
    },
    //状态显示转换
    formatState: function (row, column) {
      return row.state == 1 ? '启用' : row.state == 0 ? '停用' : '未知';
    },
    handleEdit(index,row){
      this.title = "编辑";
      // 数据的回显
      Object.assign(this.employeeForm,row);
      // 打开弹出框
      this.formVisible = true;
    },
    handleDel(index,row){
      this.$confirm('确认删除吗？', '提示', {
        type:'warning'
      }).then(() => {
        // 确认框
        this.$http.delete("/emp/"+row.id).then((res) => {
          if(res.data.success){
            this.$message({
              message: '删除成功',
              type: 'success'
            });
          }else {
            this.$message.error(res.data.message);
          }
          this.loadListData();
        });
      });
    },

    loadListData(){
      // 加载列表数据
      this.listLoading=true
      // 封装请求数据
      let query = {
        currentPage:this.currentPage,
        pageSize:this.pageSize,
        keywords:this.query.keywords
      }
      // 发送请求获取列表数据
      this.$http.post("/emp",query).then(res => {
        this.dataList = res.data.data;
        this.total = res.data.count;
        // 关闭加载效果
        this.listLoading = false;
      })
    },
    handleCurrentChange(num){
      this.currentPage = num;
      this.loadListData();
    },
    handleSizeChange(num){
      this.pageSize = num;
      this.loadListData();
    },
    loadDeps(){
      this.$http.get("/dep").then(res => {
        this.deps = res.data;
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定删除 ${ file.name }？`);
    },
    export_excel_file(export_data,list_name) {
      let link = document.createElement("a");
      //    type就是blob的type,是MIME类型的，可以自己查看MIME类型都有哪些
      let blogw = new Blob([export_data], {type: "application/vnd.ms-excel;charset=utf-8"})
      let objectUrl = window.URL.createObjectURL(blogw);    //创建一个新的url对象
      link.href = objectUrl;
      link.download = "员工表";    //  下载的时候自定义的文件名
      link.click();
      window.URL.revokeObjectURL(objectUrl);
    },
    exportData(){
      this.$http.post("/emp/export",{keywords:this.query.keywords},{responseType:'arraybuffer'}).then(res => {
        this.export_excel_file(res.data,"表格");
      })
    },
    handleImport(){
      this.title = '导入文件';
      this.uploadVisible = true;
    },
    submitUpload(){
      this.$refs.upload.submit();
    },
    httpRequest(param){
      let formObj = param.file;
      let formData = new FormData;
      formData.append('file',formObj);
      this.$http.post("/emp/import",formData,
          {headers:{ 'Content-Type': 'multipart/form-data'}})
          .then(res => {
            this.uploadVisible = false;
            if (res.data.success){
              this.$message({
                message:'上传成功',
                type:'success'
              });
              this.fileList = [];
              this.loadListData();
            }else {
              this.fileList = [];
              this.loadListData();
              this.loadErrorData();
              this.$message.error(res.data.message);
            }
          })
    },
    loadErrorData(){
      this.$http.post("/emp/errorData",null,{responseType:'arraybuffer'}).then(res => {
        this.export_excel_file(res.data);
      })
    }
  },
  mounted() {
    this.loadListData();
    this.loadDeps();
  }
}


</script>

<style scoped>

</style>